﻿using MaximServices.Model;
using MaximServices.Repository;
using System.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using DapperExtensions;
using MaximServices.Common;
using MaximServices.Enum;

namespace MaximServices.Services
{
    public class MottoServices
    {
        private MottoRepository _mottoRepository;
        private MottoRuleRepository _mottoRuleRepository;
        private ViewHistoryServices _viewHistoryServices;

        public MottoServices(MottoRepository mottoRepository, MottoRuleRepository mottoRuleRepository, ViewHistoryServices viewHistoryServices)
        {
            _mottoRepository = mottoRepository;
            _mottoRuleRepository = mottoRuleRepository;
            _viewHistoryServices = viewHistoryServices;
        }

        public List<Motto> GetList(string keyword, string status)
        {
            return _mottoRepository.GetList(keyword, status);
        }

        public ResultModel<CreateMottoResultModel> BatchCreateMotto(CreateMottoResultModel data, string tag = "", string source = "手工")
        {
            List<string> lite = new List<string>();
            data.DataList.ForEach(c => lite.Add($"'{c.contentLite}'"));

            List<Motto> conflict = _mottoRepository.GetMottoByContentLite(lite);
            if (null != conflict && 0 < conflict.Count)
            {
                List<string> con_str = new List<string>();
                conflict.ForEach(c => con_str.Add(c.Content_Lite));
                var tmp = data.DataList.Where(c => con_str.Contains(c.contentLite)).ToList();
                tmp.ForEach(c => c.isSuccess = false);
            }
            List<Motto> createModel = new List<Motto>();
            data.DataList.ForEach(c =>
            {
                if (c.isSuccess)
                {
                    createModel.Add(new Motto
                    {
                        Id = IdFactory.NextId,
                        Auth_Name = c.auth,
                        Motto_Content = c.content,
                        Content_Lite = c.contentLite,
                        Create_Time = DateTime.Now,
                        Modify_Time = DateTime.Now,
                        Source = source,
                        Baike_Url = "",
                        Status = MottoStatus.UnConfirm,
                        TagList = tag
                    });
                }
            });

            if (_mottoRepository.BatchCreate(createModel))
            {
                return BuildResult.Success(data);
            }
            else
            {
                return BuildResult.Error("添加出错了", default(CreateMottoResultModel
                    ));
            }

        }

        public ResultModel<Motto> ReviewMotto(Motto model)
        {
            model.Status = MottoStatus.Confirmed;
            if(_mottoRepository.ReviewMotto(model))
            {
                return BuildResult.Success(model);
            }
            else
            {
                return BuildResult.Error("复核失败", model);
            }
        }

        private Motto GetAll(List<string> history,string ruleId,string userId, DateTime now)
        {
            List<Motto> all = _mottoRepository.GetAllList();
            List<Motto> not = all.Where(c => !history.Contains(c.Id)).ToList();
            if (null == not || 0 == not.Count)
                return null;

            Random r = new Random();
            int random = r.Next(0, not.Count - 1);
            Motto result = not[random];
            //添加浏览历史
            _viewHistoryServices.AddHistory(new ViewHistory
            {
                Id = IdFactory.NextId,
                Create_Time = now,
                Modify_Time = now,
                Motto_Id = result.Id,
                Source_Id = ruleId,
                User_Id = userId,
                View_Date = new DateTime(now.Year, now.Month, now.Day),
            });
            return result;
        }

        public Motto GetSingleMotto(string userId, string mockDate)
        {
            //模拟时间
            DateTime now = DateTime.MinValue;

            if (!string.IsNullOrWhiteSpace(mockDate))
            {
                try
                {
                    now = Convert.ToDateTime(mockDate);
                }
                catch
                {
                    
                }
            }

            if (now == DateTime.MinValue)
            {
                now = DateTime.Now;
            }

            //ViewHistory nowHistory = _viewHistoryServices.GetNow(now, userId);
            //if(null != nowHistory)
            //{
            //    return _mottoRepository.FindMotto(nowHistory.Motto_Id);
            //}
            //List<ViewHistory> history = _viewHistoryServices.GetList(now, userId);
            List<string> mottoIds = new List<string>();
            ////所有今年展示过的
            //history.ForEach(c => mottoIds.Add(c.Motto_Id));

            //MottoRule rule = _mottoRuleRepository.GetSingleByDate(now);
            //if(null != rule)
            //{
            //    MottoRuleJsonModel objRule = Json.ToObject<MottoRuleJsonModel>(rule.Rule_Json);
            //    List<Motto> ruleSearchList = _mottoRepository.GetListByRule(objRule.keyword, objRule.Author, objRule.label);
            //    if (null != ruleSearchList && 0 < ruleSearchList.Count)
            //    {
            //        List<Motto> notHistory = ruleSearchList.Where(c => !mottoIds.Contains(c.Id)).ToList();
            //        if(null != notHistory && 0 < notHistory.Count)
            //        {
            //            Random r = new Random();
            //            int random = r.Next(0, notHistory.Count - 1);
            //            Motto result = notHistory[random];
            //            //添加浏览历史
            //            _viewHistoryServices.AddHistory(new ViewHistory
            //            {
            //                Id = IdFactory.NextId,
            //                Create_Time = now,
            //                Modify_Time = now,
            //                Motto_Id = result.Id,
            //                Source_Id = rule.Id,
            //                User_Id = userId,
            //                View_Date = new DateTime(now.Year, now.Month, now.Day),
            //            });
            //            return result;
            //        }
            //    }
            //    //允许自有匹配
            //    if(rule.Usedefault_Rule == 1)
            //    {
            //        return GetAll(mottoIds, rule.Id, userId, now);
            //    }

            //    return null;
            //}
            
            return GetAll(mottoIds, "", userId, now);
        }
    }
}
